package com.snail.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * @Author 蔡徐坤
 * @Date 2025/7/14 23:11
 * @Description: 这里的配置类为用于在插入和更新操作时自动填充createTime和updateTime字段
 */
//将类注入到spring容器中，能被启动类扫描到
@Component
public class MyBatisPlusConfig implements MetaObjectHandler {
    // 插入时自动填充createTime字段和updateTime字段
    @Override
    public void insertFill(MetaObject metaObject) {
        // 这里是调用StpUtil获取当前登录的用户名，并赋值给createBy和updateBy字段
        // 仅当createBy为空时填充（即管理员操作场景）
//        if (metaObject.getValue("createBy") != null) {
            String adminUsername = getCurrentUsername();
            this.strictInsertFill(metaObject, "createBy", String.class, adminUsername);
            this.strictInsertFill(metaObject, "updateBy", String.class, adminUsername);
//        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    // 更新时自动填充updateTime字段
    @Override
    public void updateFill(MetaObject metaObject) {
        String currentUsername = getCurrentUsername();
        this.strictUpdateFill(metaObject, "updateBy", String.class, currentUsername);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "joinTime", LocalDateTime.class, LocalDateTime.now());
    }

    // 获取当前登录的用户名
    private String getCurrentUsername() {
        if (!StpUtil.isLogin()) {
            return "system";
        }
        //从Session获取用户名
        SaSession session = StpUtil.getSession();
        String username = (String) session.get("username");
        return username != null ? username : StpUtil.getLoginIdAsString();
    }

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }
}
